<template>
    <div class="app-container" v-loading.fullscreen.lock="loading">
        <div>
            <el-form class="lookForm" label-width="120px">
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="学号">
                            <el-input size="mini" v-model="search.stuNo"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label-width="10px">
                            <el-button icon="el-icon-search" type="primary" size="mini" @click="doSearch">搜索</el-button>
                            <el-button icon="el-icon-refresh" size="mini" @click="doRefresh">重置</el-button>
                            <el-button type="success" plain icon="el-icon-plus" size="mini"
                                @click="fdyV = true">提交申请</el-button>
                            <el-button icon="el-icon-download" size="mini" type="primary"
                                @click="exportV = true">导出</el-button>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="班级">
                            <el-select style="width: 100%;" size="mini" @change="changeSelect"
                                v-model="search.className">
                                <el-option v-for="(v, i) in own_class" :key="i" :label="v.className"
                                    :value="v.classId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="学年">
                            <el-select style="width: 100%;" size="mini" @change="changeYearSelect"
                                v-model="search.stuYearName">
                                <el-option v-for="(v, i) in select_year_list" :key="i" :label="v.stuYearName"
                                    :value="v.stuYearName"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                </el-row>
            </el-form>
        </div>

        <el-table v-loading="loading" :data="data_list" style="width:100%;margin-top: -20px;">
            <el-table-column v-if="search.className != '' || search.stuYearName != ''" label="#" align="center"
                width="80">
                <template slot-scope="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column prop="stuYearName" label="学年" align="center" />
            <el-table-column prop="className" label="班级" align="center" width="300" />
            <el-table-column prop="stuName" label="学生姓名" align="center" />
            <el-table-column prop="stuNo" label="学号" align="center" />
            <el-table-column prop="score" label="思想品德成绩" align="center" />
            <el-table-column label="学生状态" align="center" prop="status">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.srs_stu_status" :value="scope.row.status" />
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-view"
                        @click="lookVClick(scope.row)">查看详情</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="listInfo" />

        <el-dialog title="辅导员提交" :visible.sync="fdyV" width="600px" append-to-body>
            <el-form ref="form" :model="fdyForm" label-width="100px">

                <el-form-item label="班级" prop="submitter">
                    <el-select @change="getClassStu" v-model="selectedClass" style="width: 400px;">
                        <el-option v-for="(v, i) in own_class" :key="i" :label="v.className"
                            :value="v.classId"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="学生" prop="stuYearId">
                    <el-select filterable v-model="selectedStu" placeholder="请先选择班级再选择学生" style="width: 400px;">
                        <el-option v-for="(v, i) in own_stu" :key="i" :label="v.stuName" :value="v.stuNo">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="学年" prop="stuYearId">
                    <el-select style="width: 400px;" v-model="fdyForm.stuYearId" placeholder="请选择学年">
                        <el-option v-for="(v, i) in stu_year_list" :key="i" :value="v.id"
                            :label="v.stuYearName"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="加分扣分项" prop="childType">
                    <el-select style="width: 400px;" v-model="childType" placeholder="请选择项目">
                        <el-option v-for="(v, i) in child_list" :key="i" :value="v.ruleId"
                            :label="v.ruleName"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="分值" prop="description">
                    <el-input style="width: 400px;" v-model="add_record" type="number" disabled placeholder="请输入内容" />
                </el-form-item>
                <el-form-item label="佐证材料" prop="material">
                    <image-upload v-model="fdyForm.material" />
                </el-form-item>

                <el-form-item label="备注" prop="description">
                    <el-input v-model="fdyForm.description" type="textarea" placeholder="请输入内容" />
                </el-form-item>


            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="fdyAdd">确 定</el-button>
                <el-button @click="fdyV = false" fit="contain">取 消</el-button>
            </div>
        </el-dialog>

        <el-dialog title="详细记录" :visible.sync="detailV" width="900px" append-to-body>
            当前学年思想品德总分(最大不超过100分) = (当前学年思想品德明细的总和) + (思想品德初始分数80分)
            <el-table :data="record_list">
                <el-table-column prop="stuYearName" label="学年" align="center" />
                <el-table-column prop="ruleName" label="项目" align="center" />
                <el-table-column label="分数" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.recordScore > 0 ? '+' + scope.row.recordScore.toString() : scope.row.recordScore }}
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="详情" align="center" />
            </el-table>
        </el-dialog>
        <el-dialog title="选择导出" :visible.sync="exportV" width="600px" append-to-body>
            <el-form label-width="120px">
                <el-form-item label="学年">
                    <el-select id="stuYearId" size="mini" style="width: 400px;" v-model="exportForm.stuYearId"
                        placeholder="请选择学年">
                        <el-option :key="i" v-for="(v, i) in select_year_list" :value="v.id"
                            :label="v.stuYearName"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="班级">
                    <el-select style="width: 400px;" size="mini" v-model="exportForm.classId">
                        <el-option v-for="(v, i) in own_class" :key="i" :label="v.className"
                            :value="v.classId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="">
                    <el-button size="mini" @click="toExport">导出</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>


    </div>
</template>
<script>
import { getIamRecordByStuNo, listIam, listAllIam } from "@/api/stuCQS/basedata/teacher";
import { fdyAdd, toExport } from "@/api/stuCQS/info-fill/iam";
import { listEnableYear as listYear } from "@/api/stuCQS/basedata/year";
import { listIamChild } from "@/api/stuCQS/basedata/cphRules";
import { isEmpty } from "@/api/helpFunc";
import { listOwnClass, listOwnStuByClass } from "@/api/stuCQS/info-fill/stu_eva_task";
import { workbook2blob, openDownloadDialog, file2Xce } from "@/api/helpFunc";
import * as XLSX from 'xlsx';
import { listAllYear as listStuYear } from "@/api/stuCQS/basedata/year";

export default {
    name: "iam",
    dicts: ['srs_stu_status'],
    data() {
        return {

            select_year_list: [],


            fdyV: false,
            own_class: [],
            own_stu: [],
            selectedClass: null,
            selectedStu: null,
            fdyForm: {
                description: "--通过辅导员提交",
                material: ""
            },
            add_record: 0,
            childType: null,
            child_list: [],
            stu_year_list: [],

            detailV: false,

            loading: false,
            pageParams: {
                pageNum: 1,
                pageSize: 10,
            },
            record_list: [],

            data_list: [],
            queryParams: {
                pageNum: 1,
                pageSize: 10,
            },
            total: 0,
            selectedClass: null,

            all_list: [],
            exportV: false,
            search: {
                stuNo: "",
                className: "",
                stuYearName: ""
            },
            exportForm: {
                stuYearId: null,
                classId: null,
            },

        }
    },
    created() {
        this.listStuYear();

        this.listAllInfo();
        this.listOwnClass();
        this.getStuYear();
        this.listIamChild();
        this.listIam();
    },
    watch: {
        "childType"(newVal, oldVal) {
            this.child_list.map((v) => {
                if (v.ruleId == newVal) {
                    this.add_record = v.maxScore
                }
            });
        }
    },
    methods: {

        async listStuYear() {
            let res = await listStuYear();
            if (res.code == 200) {
                this.select_year_list = [...res.data];
            }
        },


        async listAllInfo() {
            this.loading = true;
            let res = await listAllIam();
            this.loading = false;
            if (res.code == 200) {
                this.all_list = [...res.data];
            }
        },
        changeSelect() {
            let className = this.search.className;
            let stuYearName = this.search.stuYearName;

            if (!isEmpty(className)) {
                let temp1 = [];
                let temp2 = [...this.all_list];
                temp2.map(x => {
                    if (!isEmpty(stuYearName)) {
                        if (x.className == className && x.stuYearName == stuYearName) {
                            temp1.push(x);
                        }
                    } else {
                        if (x.className == className) {
                            temp1.push(x);
                        }
                    }
                });
                this.total = 0;
                this.queryParams.pageSize = temp1.length;
                this.data_list = [...temp1];
                return;
            }
        },
        changeYearSelect() {
            let className = this.search.className;
            let stuYearName = this.search.stuYearName;
            if (!isEmpty(stuYearName)) {
                let temp1 = [];
                let temp2 = [...this.all_list];
                temp2.map(x => {
                    if (!isEmpty(className)) {
                        if (x.stuYearName == stuYearName && x.className == className) {
                            temp1.push(x);
                        }
                    } else {
                        if (x.stuYearName == stuYearName) {
                            temp1.push(x);
                        }
                    }

                });
                this.total = 0;
                this.queryParams.pageSize = temp1.length;
                this.data_list = [...temp1];
                return;
            }
        },
        async doSearch() {
            let stuNo = this.search.stuNo;
            if (!isEmpty(stuNo)) {
                let temp1 = [];
                let temp2 = [...this.all_list];
                temp2.map(x => {
                    if (x.stuNo == stuNo) {
                        temp1.push(x);
                    }
                });
                this.total = 0;
                this.queryParams.pageSize = temp1.length;
                this.data_list = [...temp1];
                return;

            }
        },
        async doRefresh() {
            this.search.stuNo = "";
            this.search.className = "";
            this.search.stuYearName = "";
            this.queryParams.pageSize = 10;
            this.listInfo();
        },
        async listInfo() {
            this.loading = true;
            let res2 = await listIam(this.queryParams);
            if (res2.code == 200) {
                this.data_list = [...res2.rows];
                this.total = res2.total;
            }
            this.loading = false;

        },
        async listIam() {
            this.loading = true;
            let res1 = await listOwnClass();
            if (res1.code == 200) {
                let classes = [...res1.data];
                if (classes.length != 0) {
                    this.queryParams.classId = classes[0].classId;
                    let res2 = await listIam(this.queryParams);
                    if (res2.code == 200) {
                        this.data_list = [...res2.rows];
                        this.total = res2.total;
                    }
                }

            }
            this.loading = false;
        },
        async lookVClick(row) {
            console.log(row)
            let stuNo = row.stuNo;
            await this.getStuIam(stuNo);
            this.detailV = true;
        },
        async getStuIam(stuNo) {
            this.loading = true;
            let res = await getIamRecordByStuNo(stuNo, this.pageParams);
            this.loading = false;
            if (res.code == 200) {
                this.record_list = [...res.rows];
                console.log(this.record_list)
            }
        },

        async listOwnClass() {
            let res = await listOwnClass();
            if (res.code == 200) {
                this.own_class = [...res.data];
            }
        },
        async getClassStu() {
            let class_id = this.selectedClass;
            if (class_id != null) {
                let res = await listOwnStuByClass(class_id);
                this.own_stu = [...res.data];
            }
        },
        async fdyAdd() {
            let sdata = { ...this.fdyForm };
            if (this.selectedStu == null) {
                this.$message.info("请选择学生");
                return;
            }
            if (this.childType == null) {
                this.$message.info("请选择项目");
                return;
            }
            if (isEmpty(sdata.stuYearId)) {
                this.$message.info("请选择学年");
                return;
            }
            // if (isEmpty(sdata.material)) {
            //     this.$message.info("请上传佐证材料");
            //     return;
            // }
            if (isEmpty(sdata.description)) {
                this.$message.info("请填写描述");
                return;
            }
            let stuNo = this.selectedStu;
            let stuName = "";
            this.own_stu.map(x => {
                if (x.stuNo == stuNo) {
                    stuName = x.stuName;
                }
            })
            let classId = this.selectedClass;
            let className = "";
            this.own_class.map(x => {
                if (classId == x.classId) {
                    className = x.className;
                }
            });
            let ruleType = this.childType;
            let ruleName = "";
            this.child_list.map(x => {
                if (ruleType == x.ruleId) {
                    ruleName = x.ruleName;
                }
            });

            let add_record = this.add_record;

            let confirmMsg = `您确定要为 ${className} 的学号为 ${stuNo} 的 ${stuName} 同学加上 ${ruleName} 的 ${add_record} 分吗？`


            this.$confirm(confirmMsg, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                this.$confirm("真的确定吗?" + confirmMsg, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    sdata.stuNo = this.selectedStu;
                    sdata.ruleId = this.childType;
                    this.loading = true;
                    let res = await fdyAdd(sdata);
                    this.loading = false;
                    if (res.code == 200) {
                        this.$message.success(res.msg + ",若操作失误请联系学工处");
                        this.fdyV = false;

                        this.listAllInfo();
                        this.listOwnClass();
                        this.getStuYear();
                        this.listIamChild();
                        this.listIam();

                    }
                })
            })


        },
        async getStuYear() {
            let res = await listYear();
            this.stu_year_list = [...res.rows];
        },
        async listIamChild() {
            let res = await listIamChild();
            this.child_list = [...res.data];
        },
        async toExport() {
            if (isEmpty(this.exportForm.stuYearId)) {
                this.$message("请选择学年");
                return;
            }
            if (isEmpty(this.exportForm.classId)) {
                this.$message("请选择班级");
                return;
            }

            this.loading = true;
            console.log(this.exportForm)
            let res = await toExport(this.exportForm);
            this.loading = false;
            if (res.code == 200) {
                let data = res.data;
                const header = ['1学年', '2学院', '3专业', '4班级', '5学号', '6姓名', '7思想品德', '8班级排名', '9专业排名', '10学生状态', '11导出时间'];
                const header_zh = {
                    '1学年': '1学年',
                    '2学院': '2学院',
                    '3专业': '3专业',
                    '4班级': '4班级',
                    '5学号': '5学号',
                    '6姓名': '6姓名',
                    '7思想品德': '7思想品德',
                    '8班级排名': '8班级排名',
                    '9专业排名': '9专业排名',
                    '10学生状态': '10学生状态',
                    '11导出时间': '11导出时间'
                };

                const arrayWithHeader = [header_zh, ...data];

                var sheet1 = XLSX.utils.json_to_sheet(arrayWithHeader,
                    {
                        header: header,
                        skipHeader: true
                    });
                sheet1["!cols"] = [
                    { wch: 15 },
                    { wch: 20 },
                    { wch: 20 },
                    { wch: 25 },
                    { wch: 12 },
                    { wch: 12 },
                    { wch: 12 },
                    { wch: 12 },
                    { wch: 12 },
                    { wch: 12 },
                    { wch: 12 },
                    { wch: 12 },
                    { wch: 12 },
                    { wch: 12 }
                ];

                // 创建一个新的空的workbook
                var wb = XLSX.utils.book_new();
                // 为每一个工作簿设置名称并添加到workbook（excel表）中
                XLSX.utils.book_append_sheet(wb, sheet1, "思想品德");
                const workbookBlob = workbook2blob(wb);  // 辅助函数workbook2blob
                // 下载文档并添加文件名称
                openDownloadDialog(workbookBlob, "思想品德.xlsx");  // 辅助函数openDownloadDialog

            }
        },
    }
}
</script>
<style scoped lang="scss">
.lookForm {
    .el-form-item {
        margin-bottom: 5px;
    }
}
</style>